<template>
  <div :class="{'invite-order': isInviteOrder}" class="order-select-container">
    <DetailTabs v-model="activeTab" :tabs="tabList" @tabClick="tabClick"/>
    <div class="supplier-order-select">
      <template v-if="hasRouteAuth('medium:supplierAudit:launch')">
        <div v-if="activeTab !== 3" :class="{'mobileCostGroup': showMobilePage}" class="cost-group">
          <div style="white-space: nowrap; font-size: 14px; margin-right: 12px;">
            <span style="color: #999">已选：</span>{{ costIdList.length }}项
          </div>
          <el-tag
            v-for="tag in stepOneData.selectCost"
            :key="tag.id"
            :class="costIdList.includes(tag.id) ? '' : 'cost-not-active'"
            :closable="!isInviteOrder"
            class="cost-tag"
            @click.native="onCostChange(tag.id)"
            @close="deleteCost(tag.id)">
            {{ tag.name }}
          </el-tag>
        </div>
        <OrderSelectTable
          v-show="activeTab === 1"
          ref="orderSelectTableRef"
          :cost-id="costIdList"
          :step-one-data="stepOneData"
          :supplier-id="stepOneData.supplierId"
          :cost-belong="stepOneData.costBelong"
          :step-two-data="stepTwoData"
          :is-invite-order="isInviteOrder"
          :is-add-cost="isAddCost"
          @selectData="selectOrderFunc"
        />
        <CostTable
          v-show="activeTab === 2"
          ref="costSelectTableRef"
          :cost-id="costIdList"
          :supplier-id="stepOneData.supplierId"
          :step-two-data="stepTwoData"
          :is-invite-order="isInviteOrder"
          :is-add-cost="isAddCost"
          @selectData="selectCostFunc"
        />
        <AllSelectedTable
          v-show="activeTab === 3"
          :select-order-list="selectOrderList"
          :select-cost-list="selectCostList"
          :cost-belong="stepOneData.costBelong"
          @orderSelectedReset="orderSelectedReset"
          @costSelectedReset="costSelectedReset"
        />
      </template>
      <empty-placeholder v-if="(stepOneData && stepOneData.selectCost && stepOneData.selectCost.length === 0) || !stepOneData" />
      <empty-placeholder v-else-if="!hasRouteAuth('medium:supplierAudit:launch')" text="暂无权限" />
      <fixed-pagination v-if="!isAddCost && !isInviteOrder && stepOneData && stepOneData.selectCost && stepOneData.selectCost.length">
        <div class="center">
          <el-button v-if="!otherDetail && hasRouteAuth('medium:supplierAudit:launch')" type="primary" size="small" class="pre-step plain-create-btn" @click="backCost">上一步</el-button>
          <el-button v-if="hasRouteAuth('medium:supplierAudit:launch')" :loading="supplierSubmitLoading" class="mobile-btn-flex" size="small" type="primary" @click="submitCost">下一步</el-button>
          <back-btn text="返回列表" />
        </div>
      </fixed-pagination>
    </div>
    <div
      v-if="isInviteOrder && stepOneData && stepOneData.selectCost && stepOneData.selectCost.length"
      class="is-absolute-tool">
      <el-button
        :loading="supplierSubmitLoading"
        :disabled="!selectOrderList.length && !selectCostList.length"
        size="small"
        class="mobile-btn-flex"
        type="primary"
        @click="onSubmitOrder">确定</el-button>
    </div>
  </div>
</template>
<script>
/**
 * 付款申请第二步骤：审批项选择
 */
// components
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import BackBtn from '@/components/SupplierComponent/module/backBtn';
import OrderSelectTable from './OrderSelectTable';
import CostTable from './CostTable.vue';
import AllSelectedTable from './AllSelectedTable.vue';
// api
import { supplierSubmit, addSettleOrder, validateExamine } from '@/api/supplier';
// utils
import { hasRouteAuth } from '@/utils/permission';
import ElMessage, { showModal } from '@/utils/message';
import { mapState } from 'vuex';
import math from '@/utils/math';

export default {
  components: { DetailTabs, EmptyPlaceholder, BackBtn, OrderSelectTable, CostTable, AllSelectedTable },
  model: {
    prop: 'stepTwoData',
    event: 'changeValue'
  },
  props: {
    stepOneData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    stepTwoData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    settleId: {
      type: String | Number,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isInviteOrder: { // 协作订单
      type: Boolean,
      default: false
    },
    isAddCost: { // 是否从新增成本那里过来
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: 1,
      costIdList: [],
      otherDetail: false,
      supplierSubmitLoading: false,
      selectOrderList: [],
      selectCostList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isInvite() {
      return !!this.stepOneData.isInvite;
    },
    tabList() {
      return [
        { id: 1, name: '订单' },
        { id: 2, name: '成本' },
        { id: 3, name: `已选(${this.selectOrderList.length + this.selectCostList.length})` }
      ];
    }
  },
  created() {
    /**
     * 从成本管理过来
     */
    const costItemId = Number(this.$route.query.costItemId) || null; // 成本项ID
    const relatedOrderId = Number(this.$route.query.relatedOrderId) || null; // 关联订单ID
    // 无关联订单id，tab切换至成本
    if (!relatedOrderId && costItemId) {
      this.activeTab = 2;
    } else {
      this.activeTab = 1;
    }
    /**
     * 设置默认成本项
     */
    if (this.stepOneData && this.stepOneData.selectCost && this.stepOneData.selectCost.length > 0) {
      this.costIdList = this.stepOneData.selectCost.map(cost => cost.id);
    }
    this.otherDetail = this.$route.query.otherDetail || false; // 是否从详情页结算过来，隐藏上一步
  },
  methods: {
    hasRouteAuth,
    /**
     * 提交时获取所选中的订单或成本
     * 规则：订单或选择成本方式仅能二选一
     *
     */
    getSubmitCostParams() {
      return new Promise((resolve, reject) => {
        const ans = [];
        if (this.stepOneData.selectCost && this.stepOneData.selectCost.length) {
          this.stepOneData.selectCost.forEach(i => {
            ans.push({
              costId: i.id,
              name: i.name,
              orderIds: this.selectOrderList.filter(cost => cost.costId === i.id),
              orderCostItemIds: this.selectCostList.filter(cost => {
                if (cost.costItemId === i.id) {
                  cost.orderCostItemId = cost.id;
                }
                return cost.costItemId === i.id;
              })
            });
          });
          // if (allSelectOrderIds.length > 0 && allSelectCostIds.length > 0 && !this.isInvite) {
          //   reject('选择订单或选择成本方式仅能二选一');
          // }
          if (!this.selectOrderList.length && !this.selectCostList.length && !this.isInvite) {
            reject('请勾选需要结算的订单/成本');
          } else {
            resolve(ans);
          }
        } else {
          reject('请勾选需要结算的订单/成本');
        }
      });
    },
    async submitCost() {
      try {
        const params = {
          id: this.stepOneData.supplierId,
          costBelong: this.stepOneData.costBelong,
          settlementMethod: this.stepOneData.settlementMethod,
          isInvite: this.isInvite,
          cost: []
        };

        const cost = await this.getSubmitCostParams();
        params.cost = cost;
        // 从审批记录编辑而来
        if (this.isEdit) {
          params.settleId = this.settleId;
        }
        this.$emit('changeValue', params); // 把值赋值给 stepTwoData

        // 计算选中值的结算金额;
        const orderPrice = this.$refs['orderSelectTableRef'].totalPrice || 0;
        const costPrice = this.$refs['costSelectTableRef'].totalPrice || 0;

        // 暂时注释新功能
        // 如果不是协作请款，则不进行保存草稿，直接下一步
        // 因为协作请款在下一步需要邀请别人 填写，所以需要提前生成结算单，这样才有链接可以进行分享
        if ((!this.isInvite && !this.isEdit) || this.isAddCost) {
          try {
          // 校验所选择的订单是否可以发起审批
            const res = await validateExamine(params);
            if (res.code === 200) {
              this.$emit('selectCallback', {
                id: this.settleId || '',
                // 收款人列表的订单结算金额，创建时需要自己计算
                totalPrice: math.add(orderPrice, costPrice),
                selectCost: cost
              });
            }
          } catch (error) {
            console.log(error);
          }
          return;
        }
        if (this.isInvite) {
          params.isInvite = true;
        }

        this.supplierSubmitLoading = true;

        supplierSubmit(params).then(res => {
          if (res.code === 200) {
            ElMessage.success('选择成功');
            this.$emit('selectCallback', {
              id: res.data,
              // 收款人列表的订单结算金额，创建时需要自己计算
              totalPrice: math.add(orderPrice, costPrice),
              selectCost: cost
            });
          }
          this.supplierSubmitLoading = false;
        }).catch(err => {
          this.supplierSubmitLoading = false;
          console.error(err);
        });
      } catch (error) {
        ElMessage.error(error);
        console.log(error);
      }
    },
    tabClick() {
    },

    onCostChange(id) {
      if (this.costIdList.includes(id)) {
        this.costIdList = this.costIdList.filter(i => i !== id);
      } else {
        this.costIdList.push(id);
      }
    },
    // 已选订单/成本取消勾选移除
    orderSelectedReset(selection) {
      this.$refs['orderSelectTableRef'].multipleSelectionAll = selection;
      this.$refs['orderSelectTableRef'].removeSelect(selection);
      this.$refs['orderSelectTableRef'].tableSelectionChange(selection);
      this.$refs['orderSelectTableRef'].resetSelectStatus();
    },
    costSelectedReset(selection) {
      this.$refs['costSelectTableRef'].multipleSelectionAll = selection;
      this.$refs['costSelectTableRef'].removeSelect(selection);
      this.$refs['costSelectTableRef'].tableSelectionChange(selection);
      this.$refs['costSelectTableRef'].resetSelectStatus();
    },
    deleteCost(deleteCostId) {
      let selectList = [];
      if (this.stepOneData.selectCost.length === 1) {
        this.$confirm('删除后将返回到【成本选择】', '', {
          confirmButtonText: '确认',
          cancelButtonText: '再想想',
          type: 'warning',
          lockScroll: false,
          center: true,
          customClass: 'del-message del-message-cancel',
          iconClass: 'del-icon'
        }).then(() => {
          selectList = this.stepOneData.selectCost.filter(i => i.id !== deleteCostId);
          this.stepOneData.selectCost = selectList;
          this.$emit('setStepId', { process: 0 });
        });
      } else {
        showModal('该分类下已勾选的数据将被移除，确定删除吗？').then(() => {
          selectList = this.stepOneData.selectCost.filter(i => i.id !== deleteCostId);
          this.stepOneData.selectCost = selectList;
          this.costIdList = this.costIdList.filter(i => i !== deleteCostId);
          // 移除已删除成本分类下已选中的数据
          const currAllSelectOrderList = this.$refs['orderSelectTableRef'].multipleSelectionAll;
          const currAllSelectCostList = this.$refs['costSelectTableRef'].multipleSelectionAll;
          this.orderSelectedReset(currAllSelectOrderList.filter(order => order.costId !== deleteCostId));
          this.costSelectedReset(currAllSelectCostList.filter(order => order.costItemId !== deleteCostId));
        });
      }
    },
    // 返回上一步
    backCost() {
      this.$emit('changeValue', { cost: [] });
      this.costIdList = [];
      this.$emit('setStepId', { process: 0 });
    },
    /**
     * 协作请款
     */
    selectOrderFunc(multipleSelectionAll) {
      this.selectOrderList = multipleSelectionAll;
    },
    selectCostFunc(multipleSelectionAll) {
      this.selectCostList = multipleSelectionAll;
    },
    async onSubmitOrder() {
      const params = {
        settleId: this.settleId,
        cost: []
      };
      const cost = await this.getSubmitCostParams();
      params.cost = cost;
      this.supplierSubmitLoading = true;
      addSettleOrder(params).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
          this.$emit('submitCostAndOrder');
          this.selectOrderIds = [];
          this.selectCostIds = [];
          this.supplierSubmitLoading = false;
        }
      }).catch(err => {
        this.supplierSubmitLoading = false;
        console.error(err.message);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.order-select-container {
  padding: 0 24px;
}
.invite-order {
  padding: 0;
  padding-bottom: 56px;
}
.supplier-order-select {
  position: relative;
  // padding-bottom:40px;
  .filter-container {
    width: 400px !important;
  }
  & ::v-deep {
    .el-table::before {
      border: none;
      height: 0;
    }
    .el-select__tags {
      // overflow: hidden;
      // height: 100%;
      display: flex;
      align-items: center;
      max-width: 100%!important;
    }
    .el-tag.el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
    }
  }
  .pre-step {
    background-color: #fff;
    color: #406EFF;
    border-color: #406EFF !important;
    &:hover {
      background-color: #406EFF !important;
      color: #fff !important;
    }
  }
}
.cost-group {
  position: absolute;
  display: flex;
  align-items: center;
  right: 0;
  padding-bottom: 6px;
  max-width: calc(100% - 450px);
  @include scrollBar($x: auto, $y: hidden, $width: 6px);
}
.mobileCostGroup {
  position: static;
  max-width: 100%;
  margin-top: 12px;
}
.cost-tag {
  margin-right: 12px;
  border: 1px solid #406EFF;
  cursor: pointer;
}
.cost-tag:last-child {
  margin-right: 0;
}
.cost-not-active {
  color: #192452 !important;
  border: none !important;
  background-color: #F5F5F5 !important;
  & ::v-deep {
    .el-tag__close {
      color: #121938 !important;
    }
    .el-tag__close:hover {
      background-color: #ccc !important;
    }
  }
}

.is-absolute-tool {
  position: absolute;
  width: 100%;
  bottom: 0px;
  z-index: 11;
  background: #fff;
  height: 50px;
  display: flex;
  align-items: center;
}
</style>
